package civaid;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JSONServlet extends HttpServlet {

	private static final long serialVersionUID = -947667648035113668L;

	private Logger log = Logger.getLogger(JSONServlet.class.getName());
	
	private static final String JSONContentType= "application/json";
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {

		
		String path = request.getPathInfo();
		if (path==null) path="";
		if (path.startsWith("/") && !path.isEmpty()) path = path.substring(1);
		String ct = request.getContentType();
		log.fine("calling: "+path+" "+ct);
		if (ct==null || !ct.contains("json")) {
			log.fine("not json request, sending error response");
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
				
		Object reply = doJSON(path, new Parameters(request));
		
		if (reply!=null) {

			response.setContentType(JSONContentType);
			response.setCharacterEncoding("utf-8");
			JSON.toJson(reply, response.getOutputStream());
		}
		else {
			log.fine("error when processing json request, sending error response");
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
			
		}
	}
	
	protected Object doJSON(String path, Parameters parameters) {
		return null;
	}

	
}
